"""
Copyright (c) 2012, Nimar S. Arora, nimar.arora@gmail.com
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

    Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.
    
    Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in
    the documentation and/or other materials provided with the
    distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
from optparse import OptionParser
import matplotlib.pyplot as plt
import numpy as np
import sys

from calvisa.utils import meta as metautils
from calvisa.utils import anss as anssutils
from calvisa.utils import elarm as elarmutils
from calvisa.utils.geog import TTTable
import calvisa.priors.events
import calvisa.priors.attenuation
import calvisa.priors.traveltime

MODELS = ["events", "attenuation", "detection",
          "traveltime", "false"]
def main():
  parser = OptionParser(usage = "Usage: %prog [options] models..\n" +
   "where model is one of events, attenuation, detection, traveltime," +
                        "or false\n" + "(use 'all' for training all models)" )
  parser.add_option("-g", "--gui", dest="gui", default=False,
                    action="store_true", help="visualize the model")
  parser.add_option("-m", "--metafile", dest="metadatafile", default="meta.txt",
                    type = "str", help="metadata file (meta.txt)")
  (options, args) = parser.parse_args()

  if len(args) == 1 and args[0] == "all":
    args = MODELS
  else:
    if len(args) == 0:
      print "error: no model specified for training"
      parser.print_usage()
      sys.exit(1)
    else:
      for arg in args:
        if arg not in MODELS:
          print "error: no such model", arg
          parser.print_usage()
          sys.exit(1)
  
  metadata = metautils.read_meta(options.metadatafile)
  start_time = metadata['train_start_time']
  end_time = metadata['train_end_time']
  tttable = TTTable(metadata['param_regional_traveltime'])
  
  # read the ground truth events
  if "events" in args:
    catalog_events = anssutils.read_catalog(metadata['true_events_catalog'])
    # TODO filter events only within start and end_time
    print "%d events read from %s" % (len(catalog_events),
                                      (metadata['true_events_catalog']))

  if ("attenuation" in args or "traveltime" in args):
    events = elarmutils.read_events(metadata['train_events'], start_time,
                                    end_time)
    assocs = elarmutils.read_assocs(metadata['train_assocs'], start_time,
                                    end_time)
    # triggers = read_triggers(metadata['triggers'], start_time, end_time)
    # assocs = read_assocs(metadata['train_assocs'], start_time, end_time)
    # TODO: read events and detections
    pass
   
  
  # train the events model
  if "events" in args:
    calvisa.priors.events.train(options, metadata, catalog_events)

  # train the attenuation model
  if "attenuation" in args:
    calvisa.priors.attenuation.train(options, metadata, events, assocs)

  # train the travel time model
  if "traveltime" in args:
    calvisa.priors.traveltime.train(options, metadata, tttable, events, assocs)
    
  if options.gui:
    plt.show()
  
if __name__ == "__main__":
  np.seterr(over='raise')
  try:
    main()
  except SystemExit:
    raise
  except:
    import pdb, traceback, sys
    traceback.print_exc(file=sys.stdout)
    pdb.post_mortem(sys.exc_traceback)
    raise
